import { history, request, useRequest } from '@umijs/max';
import { Button, Popconfirm, Table } from 'antd';

const TemplateList = () => {
  const {
    run: getList,
    loading,
    data: list,
  } = useRequest(() => {
    return request('/api/template', {
      method: 'GET',
    });
  });

  const { run: deleteTemplate } = useRequest(
    (id: number) => {
      return request(`/api/template/${id}`, {
        method: 'DELETE',
      });
    },
    {
      manual: true,
    },
  );

  const columns = [
    { title: '名称', dataIndex: 'name' },
    { title: '描述', dataIndex: 'description' },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_: any, record: any) => (
        <>
          <Button
            type="text"
            onClick={() => {
              history.push({
                pathname: '/template/edit',
                search: `?id=${record.id}&preview=1`,
              });
            }}
          >
            编辑
          </Button>
          <Button
            type="text"
            onClick={() => {
              history.push({
                pathname: '/template/preview',
                search: `?id=${record.id}&preview=0`,
              });
            }}
          >
            预览
          </Button>
          <Popconfirm
            title="删除模板"
            description={`确定要删除模板 ${record.name} 吗？`}
            onConfirm={async () => {
              await deleteTemplate(record.id);
              await getList();
            }}
          >
            <Button type="text">删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <Table
      columns={columns}
      dataSource={list?.rows}
      loading={loading}
      pagination={{ total: list?.total }}
    />
  );
};

export default TemplateList;
